<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------

/**
 * Created by PhpStorm.
 * Script Name: Menu.php
 * Create: 2020/6/7 上午10:26
 * Description: 自定义菜单
 * @link https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html   微信官方开发文档
 * @link https://www.easywechat.com/docs/4.1/official-account/menu  easywechat文档
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\mp\controller;

use app\common\facade\KyTree;
use think\Db;
use think\facade\Log;

class Menu extends Base
{
    /**
     * @var \think\Model
     */
    private $menuM;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->menuM = model('mpMenu');
    }

    /**
     * 保存菜单
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function savePost(){
        if(request()->isPost()){
            $post_data = input('post.');
            $menu_list = $post_data['menu_list'];
            $mp_menu = [];  //提交微信的菜单数组
            $ids = []; //保留旧数据
            foreach ($menu_list as $k => $menu){
                if(empty($menu['name'])){
                    $this->error('所有菜单的名称必填');
                }
                if(empty($menu['_child'])){
                    if(empty($menu['type']) || (empty($menu['key']) && empty($menu['url']) && empty($menu['appid']) && empty($menu['pagepath']))){
                        $this->error('【'.$menu['name'] . '】菜单的信息填写不完整');
                    }
                }else{
                    foreach ($menu['_child'] as $j => $child){
                        if(empty($child['name'])){
                            $this->error('所有菜单的名称必填');
                        }
                        if(empty($child['type']) || (empty($child['key']) && empty($child['url']) && empty($child['appid']) && empty($child['pagepath']))){
                            $this->error('【'.$child['name'] . '】菜单的信息填写不完整');
                        }
                    }
                }

                $data = [
                    'name' => $menu['name'],
                    'sort' => $k,
                    'type' => $menu['type'],
                    'key'  => $menu['key'],
                    'url'  => $menu['url'],
                    'appid' => $menu['appid'],
                    'pagepath' => $menu['pagepath']
                ];
                $mp_menu_top = [ //提交微信的一级菜单
                    'name' => $menu['name'],
                ];
                if(!empty($menu['id'])){
                    $ids[] = $menu['id'];
                    $data['id'] = $menu['id'];
                    $top_menu = $this->menuM->updateOne($data);
                }else{
                    $data['mpid'] = $this->mpId;
                    $data['pid'] = 0;
                    $top_menu = $this->menuM->addOne($data);
                }
                if(!empty($menu['_child'])){
                    $mp_menu_top['sub_button'] = [];
                    foreach ($menu['_child'] as $j => $child){
                        array_push($mp_menu_top['sub_button'], [
                            'name' => $child['name'],
                            'type' => $child['type'],
                            'key'  => $child['key'],
                            'url'  => $child['url'],
                            'appid' => $child['appid'],
                            'pagepath' => $child['pagepath']
                        ]);

                        $child_data = [
                            'pid' => $top_menu['id'],
                            'name' => $child['name'],
                            'sort' => $j,
                            'type' => $child['type'],
                            'key'  => $child['key'],
                            'url'  => $child['url'],
                            'appid' => $child['appid'],
                            'pagepath' => $child['pagepath']
                        ];
                        if(!empty($child['id'])){
                            $ids[] = $child['id'];
                            $child_data['id'] = $child['id'];
                            $this->menuM->updateOne($child_data);
                        }else{
                            $child_data['mpid'] = $this->mpId;
                            $this->menuM->addOne($child_data);
                        }
                    }
                }else{
                    $mp_menu_top = array_merge($mp_menu_top, [
                        'type' => $menu['type'],
                        'key'  => $menu['key'],
                        'url'  => $menu['url'],
                        'appid' => $menu['appid'],
                        'pagepath' => $menu['pagepath']
                    ]);
                }
                array_push($mp_menu, $mp_menu_top);
            }

            if(count($mp_menu)){
                //删除废弃的菜单
                if($ids){
                    $del_ids = $this->menuM->getField('id', ['id' => ['notin', $ids]]);
                    count($del_ids) && $this->menuM->delBatch($del_ids);
                }

                $res = $this->mpApp->menu->create($mp_menu);
                if($res['errcode'] > 0){
                    $this->error('发布失败,失败原因:' . $res['errmsg']);
                }else{
                    $this->success('发布成功');
                }
            }else{
                $this->error('请提交菜单数据');
            }
        }
    }

    /**
     * 自定义菜单设置
     * @return mixed
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        if($this->mpInfo['verify_type_info'] < 0 && $this->mpInfo['service_type_info'] != 2){
            $this->error('当前公众号未获得自定义菜单编辑权限');
        }

        $total = $this->menuM->total(['mpid' => $this->mpId], 1);
        if($total < 1){
            $this->coverMenu();
        }
        $menu_list = $this->menuM->getAll([
            'where' => ['mpid' => $this->mpId],
            'order' => ['sort' => 'asc'],
            'refresh' => 1,
            'field' => 'id,pid,name,type,sort,key,url,appid,pagepath'
        ]);
        if(count($menu_list)){
            foreach ($menu_list as &$value){
                $value['selected'] = 0;
                $value['_child'] = [];
            }
            $menu_list = KyTree::listToTree($menu_list);
        }
        $assign = ['menu_list' => json_encode($menu_list), 'types' => $this->menuM->types()];
        return $this->show($assign);
    }

    /**
     * 使用公众号菜单覆盖本地保存的菜单
     * button: [
     *      {
                "type": "text",
                "name": "text",
                "value": "This is text!"
            },
     *      {
                "name": "button",
                "sub_button": {
                    "list": [
                    {
                        "type": "view",
                        "name": "view_url",
                        "url": "http://www.qq.com"
                    },
     *          ]
     *      }
     * ]
     * @author: fudaoji<fdj@kuryun.cn>
     */
    private function coverMenu(){
        $mp_menu = $this->mpApp->menu->current();
        Db::startTrans();
        try {
            if(isset($mp_menu['selfmenu_info']['button']) && count($mp_menu['selfmenu_info']['button'])){
                $button_list = $mp_menu['selfmenu_info']['button'];
                $insert_data = [];
                foreach ($button_list as $k1 => $top_button){
                    $top_button['mpid'] = $this->mpId;
                    $top_button['sort'] = $k1;
                    if(isset($top_button['sub_button']['list']) && count($top_button['sub_button']['list'])){
                        $new = $this->menuM->addOne(['sort' => $k1, 'mpid' => $this->mpId, 'name' => $top_button['name']]);
                        foreach ($top_button['sub_button']['list'] as $k2 => $v){
                            $v['sort'] = $k2;
                            $v['pid'] = $new['id'];
                            $v['mpid'] = $this->mpId;
                            array_push($insert_data, $v);
                        }
                    }else{
                        array_push($insert_data, $top_button);
                    }
                }
                if(count($insert_data)){
                    $this->menuM->addBatch($insert_data);
                }
            }
            Db::commit();
            $res = true;
        }catch (\Exception $e){
            Log::write($e->getMessage());
            Db::rollback();
            $res = false;
        }

        return $res;
    }
}